package hr.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import hr.entity.EmployeeOnboardingLink;
import hr.mapper.EmployeeOnboardingLinkMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 定时任务
 * @since 2023年12月17日14:09:27
 * @author 柳继纪
 */
@Component
@Slf4j
public class ScheduledTask {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private EmployeeOnboardingLinkMapper employeeOnboardingLinkMapper;

    /**
     * 每隔一分钟执行一次
     */
    @Scheduled(fixedRate = 1000 * 60)
    public void myScheduledTask() throws Exception {
        log.info("定时任务执行，当前时间：{}。 任务名：fillInOnboardingRegistrationInformation，用于清扫磁盘临时文件。目标：入职报到信息填写", LocalDateTime.now());
        while (true) {
            ZSetOperations.TypedTuple<String> fri = redisTemplate.opsForZSet().popMin("fillInOnboardingRegistrationInformation");
            // Set<String> firSet = redisTemplate.opsForZSet().range("fillInOnboardingRegistrationInformation", 0, 1);
            // ZSetOperations.TypedTuple<String> fri = firSet.stream().iterator().next();
            if (fri == null) {
                log.info("当前redis队列没有过期的要求链接");
                return;
            }
            if (fri.getScore() == null || fri.getValue() == null) {
                throw new Exception("邀约链接中存在异常的数据过期时间或者是异常的文件位置");
            }
            if (System.currentTimeMillis() > fri.getScore()) {
                log.info("此邀约链接已过期，位置：{}", fri.getValue());
                boolean delete = new File(Objects.requireNonNull(fri.getValue())).delete();
                if (!delete) {
                    throw new Exception("文件刪除异常！file： " + fri.getValue());
                }
                // 更新数据库状态为已过期
                Matcher matcher = Pattern.compile("\\d+").matcher(fri.getValue());
                EmployeeOnboardingLink onboardingReport = null;
                if (matcher.find()) {
                    String snowUrlId = matcher.group();
                    QueryWrapper<EmployeeOnboardingLink> wrapper = new QueryWrapper<>();
                    wrapper.eq("url_snow_id",snowUrlId);
                    onboardingReport = employeeOnboardingLinkMapper.selectOne(wrapper);
                }
                assert onboardingReport != null;
                // 是否已提交
                if (onboardingReport.getUrlState()==2){
                    // 已提交则不修改状态了
                    continue;
                }
                onboardingReport.setUrlState((byte) 3);
                employeeOnboardingLinkMapper.updateById(onboardingReport);
            } else {
                log.info("当前邀约链接未过期，提前结束本次定时任务");
                // 将取出来的数据重新塞回去
                Boolean add = redisTemplate.opsForZSet().add("fillInOnboardingRegistrationInformation", fri.getValue(), fri.getScore());
                if (Boolean.FALSE.equals(add)) {
                    throw new Exception("定时任务被取出后重新放入任务队列出现了未知错误");
                }
                break;
            }
        }
    }
}